import gradio as gr

try:
    from conf.config import config
    from utils.constants import SPLIT_TEXT_METHOD
    from utils.originality_check import get_originality_info
except ModuleNotFoundError:
    import os
    import sys
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))  # 离开IDE也能正常导入自己定义的包
    from conf.config import config
    from utils.constants import SPLIT_TEXT_METHOD
    from utils.originality_check import get_originality_info


def get_originality(*args):
    """
    获取原创度信息
    :return:
    """
    originality_info = get_originality_info(*args)

    originality_score = originality_info.get("originality_score")
    similarity_score_ls = originality_info.get("similarity_score_ls")
    similarity_details_ls = originality_info.get("similarity_details_ls")

    return originality_score, similarity_score_ls, similarity_details_ls


def change_dropdown_split_text_method(choice: str):
    if choice == SPLIT_TEXT_METHOD["separators"]:
        return gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), gr.update(visible=False)
    elif choice == SPLIT_TEXT_METHOD["chunk_size"]:
        return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True, interactive=True)


def main():
    with gr.Blocks(theme=gr.themes.Base(),
                   title="FreeCheck") as app:
        gr.Markdown("# <center>FreeCheck")
        with gr.Tab("文章原创度检测"):
            # 输入组件
            ele_input_text = gr.Textbox(label="正文内容", placeholder="请输入正文", lines=3)
            with gr.Group():
                ele_dropdown_split_text_method = gr.Dropdown(
                    [SPLIT_TEXT_METHOD["separators"], SPLIT_TEXT_METHOD["chunk_size"]],
                    value=SPLIT_TEXT_METHOD["chunk_size"],
                    label="用什么方式切割文本，来得到句子", info="目前支持用标点符号或按字符串长度"
                )
                # 按标点符号分割
                ele_slider_min_len = gr.Slider(5, 40, value=10, step=1, visible=False,
                                               label="句子的长度最短为几个字符", info="在5到40间选择")
                ele_slider_max_len = gr.Slider(5, 40, value=20, step=1, visible=False,
                                               label="句子的长度最长为几个字符", info="在5到40间选择")
                # 按字符串长度分割
                ele_slider_chunk_size = gr.Slider(10, 40, value=config["originality_params"]["chunk_size"], step=5,
                                                  label="字符串长度达到多少就分割", info="在10到40间选择")

                ele_dropdown_k = gr.Dropdown(
                    [2, 5, 10, 15, 20], value=str(config["originality_params"]["k"]), label="选取几个句子做检测",
                    info="目前最多支持20句"
                )

            ele_radio_total_page = gr.Radio([1, 2, 3, 4, 5], value=config["originality_params"]["total_page"],
                                            label="查找百度的前几页", info="目前最多支持5页")
            ele_slider_similarity_limit = gr.Slider(10, 90, value=config["originality_params"]["similarity_limit"], step=5,
                                                    label="相似度限值", info="大于该值认为完全匹配")
            # 动作按钮
            ele_button = gr.Button("提交", variant="primary")

            # 输出组件
            ele_label_originality = gr.Label(label="原创度分数")
            ele_dataframe_similarity_ls = gr.Dataframe(
                headers=["抽取的句子", "百度相似度"],
                datatype=["str", "number"],
                row_count=(1, "dynamic"),
                col_count=(2, "fixed"),
            )
            ele_json_similarity = gr.Json(label="原创度详情")

            # 事件绑定
            ele_dropdown_split_text_method.change(
                fn=change_dropdown_split_text_method,
                inputs=ele_dropdown_split_text_method,
                outputs=[ele_slider_min_len, ele_slider_max_len, ele_slider_chunk_size]
            )
            ele_button.click(fn=get_originality,
                             inputs=[
                                 ele_input_text,
                                 ele_slider_min_len,
                                 ele_slider_max_len,
                                 ele_slider_chunk_size,
                                 ele_dropdown_k,
                                 ele_radio_total_page,
                                 ele_slider_similarity_limit
                             ],
                             outputs=[ele_label_originality, ele_dataframe_similarity_ls,
                                      ele_json_similarity, ]
                             )
        with gr.Tab("文本相似度计算"):
                ele_input_text1 = None
                ele_input_text2 = None
    app.queue(concurrency_count=10)
    app.launch(show_api=False, server_name="0.0.0.0", server_port=9099)


if __name__ == '__main__':
    main()
